import CardFunctions from "../Common/CardFunctions";
import { GameData } from "../Data/GameData";
import { BlockType, PosType } from "../Data/GameEnum";
import GameManager from "../Manager/GameManager";
import Grid from "./Grid";
import UIManager from "../Manager/UIManager";
import Block from "./Block";
import CommonFunction from "../utils/CommonFunction";
import { GameEventData } from "../Manager/GameEventManager";
import AssetsManager from "../Manager/AssetsManager";
import { ItemData } from "../Data/Level/ItemData";
import Board from "./Board";
import Card from "./Card";
import TimerManager from "../Manager/TimerManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class BlockGroup extends cc.Component {
    @property(cc.Node)
    main: cc.Node = null;

    // id和颜色相同
    id: number = 0;
    tetrisType: number = 0;
    x: number = 0;
    y: number = 0;
    length: number = 1;
    type: BlockType = BlockType.NORMAL;

    newPosition: cc.Vec3;
    initPosition: cc.Vec3;

    isDead: boolean = false;

    startPos;
    block_list: Block[] = [];
    minScale: number = 0.6;
    canMove: boolean = true;
    posType: PosType;
    angle = 0;
    time = 0;

    onLoad(): void {
    }

    // 初始化
    init(_x: number, _y: number, _id: number, _tetrisType: number, _posType: PosType) {
        this.id = _id;
        this.x = _x;
        this.y = _y;
        this.tetrisType = _tetrisType;
        this.posType = _posType;

        this.node.active = true;
        this.node.scale = this.minScale;

        this.node.position = cc.v3(0, 0, 0);

        this.startPos = this.node.position;

        this.InitBlockList();

        this.AddListener();
    }

    current = null;
    current_bg
    InitBlockList() {
        CommonFunction.SetAllChildrenAtive(this.main, false);
        this.current = this.main.children[this.tetrisType];
        this.current.active = true;
        this.current.position = cc.v3(0, 0, 0);

        this.block_list = this.current.getComponentsInChildren(Block);

        for (let index = 0; index < this.block_list.length; index++) {
            const block = this.block_list[index];
            block.id = this.id;
            block.RefreshSprite();

            const item_data = ItemData[this.id];

            // const node2 = cc.instantiate(block.icon.node);
            // node2.parent = block.icon.node.parent;
            // node2.position = cc.v3(0, 0, 0);
            // let icon2 = node2.getComponent(cc.Sprite);
            // icon2.spriteFrame = AssetsManager.图片[item_data.icon];
        }

        this.current_bg = cc.find("bg", this.current);

        let bg = cc.find("bg/bg", this.current);
        let frame = cc.find("bg/frame", this.current);
        let group = cc.find("group", this.current);
        group.active = true;

        // cc.find("bg", this.current).active = false;

        const data = ItemData[this.id];
        bg.color = new cc.Color().fromHEX(`#${data.color_bg}`);
        frame.color = new cc.Color().fromHEX(`#${data.color_frame}`);

        const 线 = cc.find("bg/线", this.current);
        for (let index = 0; index < 线.children.length; index++) {
            const child = 线.children[index];
            child.color = cc.Color.BLACK;
            child.opacity = 0.28 * 255;
        }
    }

    AddListener() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.TOUCH_START, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.TOUCH_MOVE, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.TOUCH_END, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.TOUCH_END, this);
    }

    p1
    p2
    block1;
    diffx;
    diffy;

    async TOUCH_START(t) {
        // console.log(`TOUCH_START`);

        this.time = new Date().getTime();

        CardFunctions.AllGridSelect(false);

        if (!this.canMove) {
            return;
        }

        // if (!GameData.IsCanOperate) {
        //     return;
        // }

        GameData.IsMouseDown = true;
        this.node.scale = 1;
        const location = t.getLocation();
        this.initPosition = this.node.position;
        GameData.StartPos = location;
    }

    TOUCH_MOVE(t) {
        CardFunctions.AllGridSelect(false);

        if (!this.canMove) {
            return;
        }

        // if (!GameData.IsCanOperate) {
        //     return;
        // }

        // console.log("GameData.IsMouseDown", GameData.IsMouseDown);

        if (GameData.IsMouseDown === true) {
            const location = t.getLocation();

            GameData.CurrentPos = location;
            let diff = cc.v3(GameData.CurrentPos.sub(GameData.StartPos));

            let pos = cc.v3(this.initPosition.x + diff.x, this.initPosition.y + diff.y, this.initPosition.z); // this.initPosition.add(diff);
            this.node.position = pos;

            {
                for (let index = 0; index < this.block_list.length; index++) {
                    const block: Block = this.block_list[index];
                    let p1 = block.node.convertToWorldSpaceAR(cc.v2(0, 0));
                    let p2 = UIManager.Instance.Root_grid.convertToNodeSpaceAR(p1);
                    const x_new = block.GetXByX(p2.x);
                    const y_new = block.GetXByY(p2.y);

                    let grid: Grid = CardFunctions.GetGrid(x_new, y_new)
                    if (grid && grid.block === null) {
                        grid.Select(true);
                    }
                }
            }
        }
    }

    async TOUCH_END() {
        // console.log("TOUCH_END");
        // await TimerManager.AwaitTime(0.02);

        if (!this.canMove) {
            return;
        }

        let time2 = new Date().getTime();
        let diff_time = time2 - this.time;
        if (diff_time <= 300) {
            await this.转圈();
        }

        CardFunctions.AllGridSelect(false);

        // if (!GameData.IsCanOperate) {
        //     return;
        // }

        GameData.IsMouseDown = false;

        {
            this.block1 = this.block_list[0];
            this.p1 = this.current_bg.convertToWorldSpaceAR(cc.v2(0, 0));
            this.p2 = this.block1.node.convertToWorldSpaceAR(cc.v2(0, 0));
            this.diffx = this.p1.x - this.p2.x;
            this.diffy = this.p1.y - this.p2.y;

            // console.log(this.p1.x, this.p1.y);
            // console.log(this.p2.x, this.p2.y);
            // console.log(this.p2.x - this.p1.x, this.p2.y - this.p1.y);
        }

        let fun_list = [];
        let isTag: boolean = true;

        for (let index = 0; index < this.block_list.length; index++) {
            const block: Block = this.block_list[index];

            let p1 = block.node.convertToWorldSpaceAR(cc.v2(0, 0));
            let p2 = UIManager.Instance.Root_grid.convertToNodeSpaceAR(p1);

            const x_new = block.GetXByX(p2.x);
            const y_new = block.GetXByY(p2.y);

            let grid: Grid = CardFunctions.GetGrid(x_new, y_new)
            if (grid && grid.block === null) {
                let fun = () => {
                    // this.x = x_new;
                    this.y = y_new;
                    grid.block = block;
                    block.grid = grid;
                    // block.node.parent = block.grid.node;
                    // block.node.position = cc.v3(0, 0, 0);

                    let pos1 = grid.node.convertToWorldSpaceAR(cc.v3(0, 0, 0));
                    let pos2 = block.node.parent.convertToNodeSpaceAR(pos1);
                    block.node.position = pos2;
                }
                fun_list.push(fun);

            }
            else {
                isTag = false;
                break;
            }
        }

        // await TimerManager.AwaitTime(0.02);

        if (isTag) {
            for (let index = 0; index < fun_list.length; index++) {
                const fun = fun_list[index];
                fun();
            }

            // await TimerManager.AwaitTime(0.02);

            {
                let p = this.block1.node.convertToWorldSpaceAR(cc.v3(0, 0, 0));
                let p2 = cc.v3(p.x + this.diffx, p.y + this.diffy, 0);
                this.current_bg.position = this.current_bg.parent.convertToNodeSpaceAR(p2);
            }

            this.canMove = false;
            this.posType = PosType.方格中;
            // this.node.destroy();

            CardFunctions.随机创建一个BlockGroup(this.x);

            // GameManager.Main();

            cc.systemEvent.emit(GameEventData.拖拽完成);

        }
        else {
            this.node.position = this.startPos;
            this.node.scale = this.minScale;
        }
    }

    async 转圈() {
        this.angle -= 90;
        cc.tween(this.node)
            .to(0.2, { angle: this.angle }, { easing: "" })
            .call(() => {
            })
            .start();

        await TimerManager.AwaitTime(0.2);
    }

    准备上桌() {
        for (let index_block = 0; index_block < this.block_list.length; index_block++) {
            const block: Block = this.block_list[index_block];
            for (let index_board = 0; index_board < GameData.arrBoard.length; index_board++) {
                const board: Board = GameData.arrBoard[index_board];
                console.log("board", board);
                console.log("board.cardList", board.cardList);

                for (let index_card = 0; index_card < board.cardList.length; index_card++) {
                    const card: Card = board.cardList[index_card];

                    // console.log(`card`, card);
                    // console.log(`card.node`, card.node);
                    // console.log(`card.id`, card.id);
                    // console.log(`block.id`, block.id);
                    const isBoardCover = CardFunctions.IsBoardCover(board);

                    if (card && block && card.id === block.id && block.is装填 === false && card.is装填 === false && !isBoardCover) {
                        block.is装填 = true;
                        card.is装填 = true;

                        GameData.装填list.push({
                            card: card,
                            block: block,
                            blockGroup: this,
                        })
                    }
                }
            }
        }
    }

    是否该结账了() {
        for (let index = 0; index < this.block_list.length; index++) {
            const block = this.block_list[index];
            // if (block.is装填 === false) {
            if (block.is装填完成 === false) {
                return false;
            }
        }

        return true;
    }

    async 结账() {
        const i = GameData.arrCardGroups.indexOf(this);
        if (i > -1) {
            GameData.arrCardGroups.splice(i, 1);
        }

        for (let index = 0; index < this.block_list.length; index++) {
            const block = this.block_list[index];
            block.grid.block = null;
        }

        cc.tween(this.node)
            .by(0.1, { scale: 0, y: 30 }, { easing: "" })
            .to(0.1, { scale: 0.4 }, { easing: "" })
            .call(() => {
                this.node.destroy();
            })
            .start();

        await TimerManager.AwaitTime(0.25);
    }

    // SetColor() {
    //     let colors = [0, 1, 2, 3, 4];
    //     let random_index = randomRangeInt(0, colors.length);
    //     this.color = colors[random_index];
    // }

    // SetAngle() {
    //     let angles = [0, 90, 180, 270];
    //     let random_index = randomRangeInt(0, angles.length);
    //     let angle = angles[random_index];
    //     this.node.angle = angle;
    // }

    // GetXByX(x_pos: number) {
    //     let x = (x_pos - (-GameData.W / 2 + this.node.width / 2)) / GameData.cell_width + 0.5;
    //     let x_int = Math.floor(x);
    //     return x_int;
    // }

    // GetXByY(y_pos: number) {
    //     let y = (y_pos - (-GameData.H / 2 + this.node.height / 2)) / GameData.cell_height + 0.5;
    //     let x_int = Math.floor(y);
    //     return x_int;
    // }

    // // 初始化单元宽高
    // initWidthAndHeight(cardWidth?: number, cardHeight?: number) {
    //     // if (cardWidth) this.node.width = this.icon.node.width = cardWidth * this.length;
    //     // if (cardHeight) this.node.height = this.icon.node.height = cardHeight;
    // }

    // // 初始化位置
    // InitPosition(_x = null, _y = null) {
    //     // this.node.parent = this.grid.node;
    //     // this.node.position = cc.v3(0, 0, 0);

    //     // let p1 = this.node.convertToWorldSpaceAR(cc.v2(0, 0));
    //     // let p2 = this.node.convertToNodeSpaceAR(p1);

    //     // let x = -XXL_GameConfig.W / 2 + this.node.width / 2 + XXL_GameConfig.size * _x;
    //     // let y = -XXL_GameConfig.H / 2 + this.node.height / 2 + XXL_GameConfig.size * _y;
    //     // this.node.position = cc.v3(x, y, 0);
    // }

    //
    // GetPositionXByX(_x) {
    //     let x = -GameData.W / 2 + this.node.width / 2 + GameData.cell_height * _x;
    //     return x;
    // }

    // DestroyAnimation(callback: Function = null) {
    //     if (this.isDead) {
    //         return;
    //     }

    //     this.isDead = true;

    //     const score = CardFunctions.GetScore();
    //     // GameData.SetScore(GameData.GetScore() + score);

    //     // GameData.UpdateScore();
    //     // GameFunctions.LevelUp();
    //     GamePanel.Instance.Refresh();

    //     cc.tween(this.node)
    //         .to(0.1, { opacity: 0 }, { easing: "" })
    //         .call(() => {
    //             this.node.destroy();
    //             if (callback) {
    //                 callback();
    //             }
    //         })
    //         .call(() => { })
    //         .start();
    // }

    // GetNodeWorldPostation(_node: cc.Node): cc.Vec3 {
    //     let pos: cc.Vec3 = cc.v3();
    //     if (_node.parent == null) {
    //         pos = cc.v3(_node.getPosition());
    //     } else {
    //         pos = cc.v3(_node.parent.convertToWorldSpaceAR(_node.getPosition()));
    //     }
    //     return pos;
    // }

    // ToMapData() {
    //     let data: any = {};
    //     data.id = this.id;
    //     data.type = this.type;
    //     data.x = this.x;
    //     data.y = this.y;
    //     data.length = this.length;
    //     data.color = this.color;
    //     return data;
    // }

    // Flash() {
    //     cc.Tween.stopAllByTarget(this.node);
    //     cc.tween(this.node)
    //         .repeatForever(
    //             cc.tween()
    //                 .to(0.4, { scale: 0.6 })
    //                 .to(0.4, { scale: 0.5 })
    //         )
    //         .start()
    // }

    // // 
    // GetLeftBlock(_block: Block) {
    //     const list = [];

    //     for (let index = 0; index < this.block_list.length; index++) {
    //         const block = this.block_list[index];
    //         if (_block !== block) {
    //             list.push(block);
    //         }
    //     }

    //     return list;
    // }
}